package com.handinfo.android.core.resource;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Vector;

public class ResourceList
{
	private Vector<ResHead> m_list;
	private Enumeration<ResHead> m_enum;

	public ResourceList()
	{
		m_list = new Vector<ResHead>();
		m_enum = m_list.elements();
	}

	public void reset()
	{
		m_enum = m_list.elements();
	}

	public void put(ResHead head)
	{
		m_list.addElement(head);
	}

	public void merge(ResourceList list)
	{
		reset();
		list.reset();
		ResHead head;
		while (list.hasMoreElements()) {
			head = list.nextElement();
			if (!exist(head)) {
				put(head);
			}
		}
	}

	public boolean hasMoreElements()
	{
		return m_enum.hasMoreElements();
	}

	public ResHead nextElement()
	{
		return (ResHead) m_enum.nextElement();
	}

	public boolean exist(ResHead head)
	{
		return m_list.contains(head);
	}

	public int size()
	{
		return m_list.size();
	}

	public boolean parseReceivePkg(DataInputStream dis)
	{
		try {
			m_list.removeAllElements();
			short count = dis.readShort();
			ResHead head;
			for (int j = 0; j < count; j++) {
				head = new ResHead();
				head.m_type = dis.readByte();
				head.m_url = dis.readUTF();
				head.m_version = dis.readInt();

				m_list.addElement(head);
			}
		}
		catch (IOException ex) {
			ex.printStackTrace();
			return false;
		}
		return true;
	}

	public byte[] getSendPkg()
	{
		short count = (short) m_list.size();
		try {
			ByteArrayOutputStream bao = new ByteArrayOutputStream();
			DataOutputStream dos = new DataOutputStream(bao);
			dos.writeShort(count);
			Enumeration<ResHead> enumeration = m_list.elements();
			ResHead head;
			while (enumeration.hasMoreElements()) {
				head = (ResHead) enumeration.nextElement();
				dos.writeByte(head.m_type);
				dos.writeUTF(head.m_url);
				dos.writeInt(head.m_version);

			}
			byte[] data = bao.toByteArray();
			dos.close();
			bao.close();
			dos = null;
			bao = null;
			return data;
		}
		catch (IOException ex) {
			ex.printStackTrace();
		}
		return null;
	}

	public void clean()
	{
		m_list.removeAllElements();
		reset();
	}

	public void dispose()
	{
		clean();
		m_list = null;
		m_enum = null;
	}
}
